package com.bauer.base.io.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author ：rui.wei
 * @Date ：Created in 11:29 2019/7/15
 * @Description：
 */
public class NetNioServerDemo {

    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8088));
        Selector selector = Selector.open();
        //设置非阻塞
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            //select方法为阻塞方法    防止空跑循环体
            selector.select();
            Set<SelectionKey> selectionKeySet = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeySet.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                if (SelectionKey.OP_ACCEPT == selectionKey.interestOps()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                }
                if (selectionKey.interestOps() == SelectionKey.OP_READ) {
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

                    int sum = 0;
                    try {
                        sum = socketChannel.read(byteBuffer);
                    } catch (Exception ex) {
                        socketChannel.socket().close();
                        socketChannel.close();
                        continue;
                    }

                    //当读取到的长度是-1时  客户端链接关闭了
                    if (sum == -1) {
                        socketChannel.socket().close();
                        socketChannel.close();
                    } else {
                        System.out.println("服务端收到消息-----" + new String(byteBuffer.array()));
                    }
                    byteBuffer.flip();
                }
                iterator.remove();

            }

        }


    }

}
